<template>
  <div class="field-container">
    <div class="is-select">
      <!-- <el-scrollbar class="scroll-container"> -->
      <template v-if="radioList.id || (checkList && checkList.length) || (combFieldsParams && combFieldsParams.combFields && combFieldsParams.combFields.length)">
        <el-tag
          v-if="radioList.id"
          size="small"
          class="tag"
          style="margin-right: 10px;"
          closable
          @close="delTag(radioList.id, 'radio')">
          {{ radioList.name }}
        </el-tag>
        <el-tag
          v-for="tag in checkList"
          :key="tag.name + tag.id"
          size="small"
          class="tag"
          style="margin-right: 10px;margin-bottom: 6px;"
          closable
          @close="delTag(tag.id, 'checkbox', tag.name)">
          {{ tag.name }}
        </el-tag>
        <template v-if="combFieldsParams && combFieldsParams.combFields">
          <el-tag
            v-for="(tag,index) in combFieldsParams.combFields"
            :key="tag.name + tag.id + index"
            size="small"
            class="tag combFields-tag"
            style="margin-right: 10px;margin-bottom: 6px;cursor:pointer;"
            closable
            @click="openFormulaDialog"
            @close="deleteCombFIelds(tag, index)">
            {{ tag.name }}
          </el-tag>
        </template>
      </template>
      <div v-else class="placeholder">
        请选择需要统计的字段
      </div>
      <!-- </el-scrollbar> -->
    </div>
    <div class="create-field-list">
      <div class="field-search">
        <searchField :field-list="fieldList" @setTab="setTab" />
        <div class="add-field-component">
          <div class="addbtn" @click="handelAddField">
            <!-- <img :src="addIcon" alt=""> -->
            导入字段
          </div>
          <addFieldModule
            v-if="addFieldShow"
            ref="addField"
            :radio-list="uploadField"
            @onSuccess="onSuccess" />
          <div v-if="isShowFormula" class="addbtn" style="margin-left:16px;" @click="openFormulaDialog">
            添加配置字段
          </div>
        </div>
      </div>
      <el-tabs v-if="fieldList && fieldList.length" v-model="activeName" tab-position="left" class="field-tabs">
        <el-tab-pane
          v-for="(item,index) in fieldList"
          :key="index"
          :name="item.id + ''"
          :label="item.name">
          <template slot="label">
            <div class="el-diy-tabs-label"><span v-if="item.name === '关联字段'" class="is-required" style="color:red;">*</span> {{ item.name }}</div>
          </template>
          <!-- <el-scrollbar class="scroll-container"> -->
          <!-- 多选 -->
          <div v-if="item.fieldInfo.length === 0" style="text-align:center;font-size:14px;color:#999;">暂无数据</div>
          <template v-else>
            <el-checkbox-group v-if="item.name !== '关联字段'" v-model="checkList">
              <el-form class="check-field check-box">
                <div v-for="word in item.fieldInfo" :key="word.id" class="check-field-item">
                  <el-form-item style="margin-bottom: 0;">
                    <el-checkbox :label="word" @change="checkboxChange(word,$event)" >
                      <el-tooltip v-if="word.name.length > 6" class="item" placement="top" effect="dark">
                        <div slot="content" style="max-width: 200px;">{{ word.name }}</div>
                        <span
                          :class="{
                            'searchSelectActive': selectSearchField.includes(item.id) && selectSearchField.includes(word.id)
                          }"
                          class="check-words"
                          style="position: relative;">
                          {{ word.name }}
                        </span>
                      </el-tooltip>
                      <span
                        v-else
                        :class="{
                          'searchSelectActive': selectSearchField.includes(item.id) && selectSearchField.includes(word.id)
                        }"
                        :title="word.name"
                        class="check-words"
                        style="position: relative;">
                        {{ word.name }}
                      </span>
                    </el-checkbox>
                  </el-form-item>
                  <el-form-item v-if="word.sourceShow && word.isFx === 1">
                    <el-select v-model="word.sourceId" size="small" class="select-source" popper-class="global-select-down" placeholder="请选择">
                      <el-option
                        v-for="source in word.sourceList"
                        :key="source.id"
                        :label="source.name"
                        :value="source.id"/>
                    </el-select>
                  </el-form-item>
                </div>
              </el-form>
            </el-checkbox-group>
            <el-radio-group v-else v-model="radioItem">
              <el-form class="check-field">
                <div v-for="word in item.fieldInfo" :key="word.id" class="check-field-item">
                  <el-form-item>
                    <el-radio :label="word.id" @change="radioboxChange(word,$event)" >
                      <el-tooltip v-if="word.name.length > 6" class="item" placement="top" effect="dark">
                        <div slot="content" style="max-width: 200px;">{{ word.name }}</div>
                        <span
                          :class="{
                            'searchSelectActive': selectSearchField.includes(item.id) && selectSearchField.includes(word.id)
                          }"
                          class="check-words"
                          style="position: relative;">
                          {{ word.name }}
                        </span>
                      </el-tooltip>
                      <span
                        v-else
                        :class="{
                          'searchSelectActive': selectSearchField.includes(item.id) && selectSearchField.includes(word.id)
                        }"
                        :title="word.name"
                        class="check-words"
                        style="position: relative;">
                        {{ word.name }}
                      </span>
                    </el-radio>
                  </el-form-item>
                  <el-form-item v-if="word.sourceShow && word.isFx === 1">
                    <el-select v-model="word.sourceId" size="small" class="select-source" popper-class="global-select-down" placeholder="请选择">
                      <el-option
                        v-for="source in word.sourceList"
                        :key="source.id"
                        :label="source.name"
                        :value="source.id"/>
                    </el-select>
                  </el-form-item>
                </div>
              </el-form>
            </el-radio-group>
          </template>
          <!-- </el-scrollbar> -->
        </el-tab-pane>
      </el-tabs>
      <div v-else style="text-align:center;">暂无数据</div>
      <formulaDialog
        ref="formulaDialog"
        :is-show-save-word="isShowSaveWord"
        :is-quote-template-field="isQuoteTemplateField"
        :field-list-opt="fieldListOpt"
        @setCombFields="setCombFields" />
    </div>
  </div>
</template>
<script>
import { getFieldList, getfieldSource } from '@/api/reportManage';
import searchField from './searchField.vue';
import addFieldModule from '@/components/ReportManage/selectField/addField.vue';
import addIcon from '@/assets/reportManage/add_icon.png';
import { mapState } from 'vuex';
import formulaDialog from '../formulaDialog';

export default {
  name: 'SelectField',
  components: { searchField, addFieldModule, formulaDialog },
  props: {
    value: {
      type: Array,
      default: () => {
        return [];
      }
    },
    isUploadReport: {
      type: Boolean,
      default: false
    },
    filterData: {
      type: Array,
      default: () => {
        return [];
      }
    },
    /** 公式用 */
    isShowFormula: { // 是否展示保存到报表
      type: Boolean,
      default: true
    },
    isShowSaveWord: { // 是否展示保存到报表
      type: Boolean,
      default: true
    },
    isQuoteTemplateField: { // 是否增加引用临时字段
      type: Boolean,
      default: false
    },
    fieldListOpt: { // 是否增加引用临时字段
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      addIcon,
      activeName: '1',
      searchFieldId: '',
      fieldList: [],
      checkList: [],
      radioList: {},
      radioItem: '',
      searchFieldList: [],
      selectSearchField: [],
      dialogVisible: false,
      callback: null,
      addFieldShow: false,
      combFieldsParams: {}
    };
  },
  computed: {
    ...mapState({
      'fieldListCache': state => state.options.reportFieldList
    }),
    uploadField() {
      if (this.isUploadReport) {
        return this.checkList[0] || {};
      }
      return this.radioList;
    }
  },
  created() {
    this.getField();
  },
  methods: {
    // 编辑时设置默认值
    setDefaultField(defaultField) {
      if (!defaultField) return;
      this.callback = function() {
        const fieldList = this.fieldList;
        const checkList = [];
        const fieldIdList = [];
        // 提取id列表
        fieldList.forEach(i => {
          i.fieldInfo.forEach(j => { fieldIdList.push(j.id); });
        });
        defaultField.forEach(i => {
          // 字段属性处理
          i.sourceShow = true;
          i.name = i.fieldName;
          i.sourceId = i.sourceId === 0 ? '' : i.sourceId;
          if (i.fieldId) {
            i.id = i.fieldId;
          }
          // 判断是否是上传的字段
          if (fieldIdList.includes(i.fieldId)) {
            // 不是上传字段，则与字段列表匹配
            fieldList.forEach(j => {
              j.fieldInfo.forEach(k => {
                if (i.fieldId === k.id) {
                  Object.assign(k, i);
                  // 获取字段来源列表
                  this.fieldSource(k.name, k);
                  if (j.name === '关联字段') {
                    this.radioList = k;
                    this.radioItem = k.id;
                  } else {
                    checkList.push(k);
                  }
                }
              });
            });
          } else {
            // 上传的字段直接压入
            checkList.push(i);
            this.fieldSource(i.name, i);
          }
        });
        this.checkList = checkList;
        this.setFieldList();
      };
      if (this.fieldList && this.fieldList.length) {
        this.callback();
      }
    },
    setTab(item) {
      if (item.length > 0) {
        this.activeName = item[0] + '';
      }
      this.selectSearchField = item;
    },
    async getField(name = '') {
      // if (this.fieldListCache.length <= 0 || name !== '') {
      try {
        const res = await getFieldList({ name, use: 2 });
        if (res.data) {
          res.data.forEach(i => {
            i.fieldInfo.forEach(j => {
              j.isRadio = i.name === '关联字段';
              j.sourceShow = false;
              j.sourceId = '';
              j.sourceList = [];
            });
          });
          this.fieldList = res.data;
          this.activeName = res.data[0].id + '';
          this.$store.commit('SET_REPORTFIELDLIST', res.data);
          if (this.callback) {
            setTimeout(() => {
              this.callback();
            });
          }
        }
      } catch (error) {
        console.error(error);
      }
      // } else {
      //   const fieldListCache = JSON.parse(JSON.stringify(this.fieldListCache));
      //   fieldListCache.forEach(i => {
      //     i.fieldInfo.forEach(j => {
      //       j.isRadio = i.name === '关联字段';
      //       j.sourceShow = false;
      //       j.sourceId = '';
      //       j.sourceList = [];
      //     });
      //   });
      //   this.fieldList = fieldListCache;
      // }
    },
    // 获取表格列表
    fieldSource(fieldName, item, clear = true) {
      this.$emit('getfilterData');
      setTimeout(() => {
        const filter = [];
        if (this.filterData.length) {
          let filterData = JSON.parse(JSON.stringify(this.filterData));
          filterData = filterData.filter(i => {
            if (i.top === null && i.field === '') {
              return false;
            }
            return true;
          });
          filterData.forEach(i => {
            if (i.name !== '') {
              filter.push(i);
            }
          });
        }
        filter.forEach(i => {
          if (i.type === 1 && i.value === '') {
            i.value = '[]';
          }
        });
        const params = {
          fieldName: fieldName,
          filter: filter || []
        };
        getfieldSource(params).then(res => {
          if (res.data) {
            item.sourceList = res.data;
            if (clear) {
              const sourceIdList = item.sourceList.map(i => i.id);
              if (!sourceIdList.includes(item.sourceId)) item.sourceId = '';
            }
          }
        });
      }, 0);
    },
    checkboxChange(item, e) {
      if (e) {
        const currentIndex = this.checkList.length - 1;
        for (let i = 0; i < currentIndex; i++) {
          const element = this.checkList[i];
          if (element.name === item.name || this.radioList.name === item.name) {
            this.checkList.splice(currentIndex, 1);
            this.$message.error('已添加的字段里已包含该字段名');
            return;
          }
        }
      }
      if (item.isFx === 1) {
        this.fieldSource(item.name, item);
        item.sourceShow = e;
      }
      this.setFieldList();
    },
    radioboxChange(item, e) {
      for (let i = 0; i < this.checkList.length; i++) {
        const element = this.checkList[i];
        if (element.name === item.name) {
          this.radioItem = this.radioList.id;
          this.$message.error('已添加的字段里已包含该字段名');
          return;
        }
      }
      this.fieldList.forEach(i => {
        if (i.name === '关联字段' && i.fieldInfo) {
          i.fieldInfo.forEach(j => {
            j.sourceShow = false;
          });
        }
      });
      if (item.isFx === 1) {
        this.fieldSource(item.name, item);
        item.sourceShow = true;
      }
      this.radioList = item;
      this.setFieldList();
    },
    delTag(id, type, name) {
      if (type === 'radio') {
        this.radioList.sourceShow = false;
        this.radioList.sourceId = '';
        this.radioList.sourceList = [];
        this.radioItem = '';
        this.radioList = {};
      } else {
        this.checkList = this.checkList.filter(i => {
          const flag = i.id ? i.id === id : i.name === name;
          if (flag) {
            i.sourceShow = false;
            i.sourceId = '';
            i.sourceList = [];
            return false;
          } else {
            return true;
          }
        });
      }
      this.setFieldList();
    },
    onSuccess(data) {
      this.checkList = this.checkList.concat(data);
      this.setFieldList();
      this.addFieldShow = false;
    },
    handelAddField() {
      this.addFieldShow = true;
      this.$nextTick(() => {
        this.$refs.addField.dialogVisible = true;
      });
    },
    openFormulaDialog() {
      this.$nextTick(() => {
        this.$refs.formulaDialog.openDialog();
      });
    },
    setFieldList() {
      const checkList = JSON.parse(JSON.stringify(this.checkList));
      const radioList = JSON.parse(JSON.stringify(this.radioList));
      checkList.unshift(radioList);
      this.$emit('setFieldList', checkList);
    },
    /**
     * 当筛选条件变更时触发，触发时所做的判断
     * 1. 重新获取所有已选择字段的表格列表
     * 2. 并判断当前选中的表格是否在新的表格列表里面存在，不存在则置空 （在 fieldSource 里面判断）
     */
    filterChange(filterList) {
      if (this.radioList && this.radioList.name && this.radioList.isFx === 1) {
        this.fieldSource(this.radioList.name, this.radioList, true);
      }
      if (this.checkList && this.checkList.length > 0) {
        this.checkList.forEach(i => {
          if (i.isFx === 1) {
            this.fieldSource(i.name, i, true);
          }
        });
      }
    },
    // 公式处理
    setCombFields(combFieldsParams) {
      this.combFieldsParams = combFieldsParams;
      this.$emit('inputFormula', combFieldsParams.combFields);
    },
    getCombFieldsData() {
      return this.combFieldsParams;
    },
    deleteCombFIelds(tag, index) {
      this.$refs.formulaDialog.deleteCombFIelds(tag, index);
    }
  }
};
</script>
<style lang="scss" scoped>
.field-container {
  width: 616px;
  border-radius:4px;
  border:1px solid #ddd;
  padding: 12px;
  background-color: #fff;
  .is-select {
    width: 100%;
    max-height: 120px;
    min-height: 40px;
    background-color:#fff;
    border-radius:4px;
    position: relative;
    .placeholder {
      position: absolute;
      left: 50%;
      margin-left: -70px;
      color:#ccc;
      font-size:14px;
      text-align:center;
    }
    @include scrollBar($x: hidden, $y: auto);
  }
}
.scroll-container {
  width: 100%;
  height: 100%;
}
.check-field {
  display: flex;
  flex-wrap: wrap;
  margin-top: 8px;
  .check-field-item {
    position: relative;
    margin-right: 9px;
    height: 44px;
    // min-width: 100px;
    margin-bottom: 5px;
    .el-dropdown {
      position: absolute;
      top: 0;
      right: 0;
      z-index: 20;
    }
  }
}
.flex {
  display: flex;
  align-items: center;
}
.add-field-component {
  margin-left: 10px;
  display: flex;
  align-items: center;
  .addbtn {
    font-size: 14px;
    cursor: pointer;
    height: 30px;
    font-weight: 500;
    color: #192452;
    display: flex;
    align-items: center;
    justify-content: center;
  }
}
.searchSelectActive {
  color: red;
}
.check-words {
  display: inline-block;
  width: 85px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
}
</style>
<style lang="scss">
.is-select {
  .el-tag  {
    background: #F4F7FF;
    border: none;
    color:#333333;
    font-size: 14px;
    .el-icon-close {
      color: #333;
      font-size: 16px;
      &:hover {
        background:transparent
      }
    }
  }
  .combFields-tag {
    background:#FFF9F2;
    color:#FD8546;
  }
}
.create-field-list {
  margin-top: 5px;
  position: relative;
  padding-bottom: 0px;
  .field-tabs {
    // .el-tab-pane {
    //   max-height: 300px;
    // }
    .el-form-item {
      margin-bottom: 0 !important;
    }
  }
  .el-tab-pane {
    height:100%;
  }
  .el-checkbox {
    display: flex;
    align-items: center;
  }
  .el-tabs__active-bar {
    display: none;
  }
  .el-diy-tabs-label {
    height: 26px;
    // padding: 0 20px;
    width: 92px;
    text-indent: 20px;
    line-height: 26px;
    text-align: left;
    position: relative;
    .is-required {
      position: absolute;
      left: -10px;
    }
    &:hover {
      background: #F5F5F5;;
    }
  }
  .el-tabs__header {
    // width: 363px;
    // margin-bottom: 25px;
    .el-tabs__item {
      height: 30px;
      display:flex;
      align-items: center;
      padding: 0;
      line-height: 30px;
    }
  }
  .el-tabs__nav-wrap {
    &::after {
      display: none;
    }
  }
  .el-select .el-input__inner {
    width: 100px !important;
  }
  .field-search {
    // position: absolute;
    right: 10px;
    top: 5px;
    z-index: 5;
    display: flex;
    align-items: center;
    border-bottom: 1px solid #DDDDDD;
    padding-bottom: 10px;
    margin-bottom: 5px;
    .search-field-component {
      flex:1;
    }
    .el-input__inner {
      border: none;
      font-size: 14px;
      width: 150px !important;
    }
  }

  .select-source {
    // margin-top: 5px;
    .el-input {
        // height: 20px !important;
      .el-input__inner {
        height: 23px !important;
        font-size: 12px;
      }
    }

  }
  .el-radio {
    display: flex;
    align-items: center;
    .el-radio__input {
      display: flex;
      align-items: center;
      &.is-checked {
        .el-radio__inner {
          background: #fff;
          &::after {
            background-color: #406EFF;
            width: 6px;
            height: 6px;
          }
        }
      }
    }
    .el-radio__label {
      font-size: 14px;
      padding-left: 8px;
    }
  }
  .check-box {
    .el-checkbox {
     .el-checkbox__input {
       top: 1px;
     }
    }
    .el-checkbox__label {
      display: flex;
    }
  }
}
.scroll-container{
  .el-scrollbar__wrap {
    overflow-x: hidden !important ;
  }
}

</style>
